// pages/movieIndex/movieIndex.js
const movie = require("../../models/movie")
const MovieCollect = require("../../models/movieCollected")
Page({
  data: {
    value: [],
    arr: []
  },

  onLoad: async function (options) {
    console.log(options.id);
    var value = [];
    // 遍历所有数据库
    let arr = ["inTheaters", "comingSoon", "top250"];
    for (let item of arr) {
      var res = await movie(item);
      value.push(...res.data.res)
    }
    // 找到对应id
    var result = value.find(res => {
      return res._id == options.id
    })
    this.setData({
      value: result
    })
    console.log(this.data.value);

    this.transformStart(this.data.value.raiting);
  },

  transformStart(num) {
    let arr = []
    for (let i = 0; i < 5; i++) {
      if (num > 2) {
        arr.push(2)
      } else if (num > 0) {
        arr.push(Number(num.toFixed(1)))
      } else {
        arr.push(0)
      }
      num = num - 2;
    }
    this.setData({
      arr,
    })
  },

  //收藏按钮 
  async collect(event) {
    if (event.currentTarget.dataset.collected) {
      var state = false
    } else {
      var state = true
    }
    await MovieCollect(event.currentTarget.dataset.id, state);//请求收藏路由，操作数据库
    var value = this.data.value;
    value.collected = state
    this.setData({
      value,
    })
  },
})